<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="root">
    <div>
      <p>{{ name }}</p>
      <p>{{title}}</p>
      <h3>{{book.name}}</h3>
      <h3>{{ book.totalPage }}</h3>
      <h3>{{book.nothing}}</h3>
    </div>
  </div>

  <script>
    // 1. 拿到模板
    let tmpNode = document.querySelector("#root")
    // 2. 拿到数据
    let data = {
      name: 'hang',
      title: 'learn vue',
      book: {
        name: "you dont know js",
        totalPage: 345,
        author: 'nigulas'
      }
    }

    let rKuohao = /\{\{(.+?)\}\}/g;

    // 3. 将数据放到模板中
    // 递归元素，找到模板中对应的插值
    // 现在这个案例中template是DOM元素
    // 真正的vue源码是DOM -> 字符串模板 -> VNode -> 真正的DOM 
    function compiler(template, data){
      let childNodes = template.childNodes
      // console.log("childNodes ==> ", childNodes);
      for(let i = 0; i < childNodes.length; i++){
        const type = childNodes[i].nodeType
        // nodeType 1:元素 3:文本节点
        if(type === 1){
          compiler(childNodes[i], data)
        }else if(type === 3){
          let content = childNodes[i].nodeValue
          console.log("content ==> ", content);
          content = content.replace(rKuohao, ( _, g ) => {
            let path = g.trim()
            // let key = data[trim]
            let value = getValueByPath(data, path)
            return value
          })
          childNodes[i].nodeValue = content
        }
      }
    }

    function getValueByPath(data, path){
      let paths = path.split(".")
      let value = null
      let res = data
      while(value = paths.shift()){
        res = res[value]
      }
      return res
    }

    // 利用模板生成一个 需要被渲染的 HTML 标签 （准 真正在页面中显示的 标签）
    let generateNode = tmpNode.cloneNode(true)

    compiler(generateNode, data)

    // 4. 将渲染好的 HTML 加到页面中
    root.parentNode.replaceChild(generateNode, root)

  </script>
</body>
</html>